package com.zx.cloud.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zx.cloud.stock.model.StockTbl;
import com.zx.cloud.stock.mapper.StockTblMapper;
import com.zx.cloud.stock.service.StockTblService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhaoxuan
 * @since 2021-12-22
 */
@Service
@Slf4j
public class StockTblServiceImpl extends ServiceImpl<StockTblMapper, StockTbl> implements StockTblService {

    @Autowired
    private StockTblMapper stockTblMapper;

    /**
     * 减库存
     *
     * @param commodityCode
     * @param count
     */
    //@GlobalTransactional
    //@Transactional(rollbackFor = Exception.class)
    @Override
    public void deduct(String commodityCode, int count) {
        log.info("当前 XID: {}", RootContext.getXID());
        if (commodityCode.equals("product-2")) {
            throw new RuntimeException("异常:模拟业务异常:stock branch exception");
        }

        QueryWrapper<StockTbl> wrapper = new QueryWrapper<>();
        wrapper.setEntity(new StockTbl().setCommodityCode(commodityCode));
        StockTbl stock = stockTblMapper.selectOne(wrapper);
        stock.setCount(stock.getCount() - count);

        stockTblMapper.updateById(stock);
    }

}
